<style rel="stylesheet/scss" lang="scss" >
.pro-gzq-home-log {
  .searchbar {
    padding: 10px 20px;
    color: #6a7794;
    background: #f5f7fe;
    font-size: 14px;
    .inputbox {
      display: inline-block;
      margin-left: 10px;
      // border: 1px solid #ddd;
      // background: #ffffff;
      // border-radius: 4px;
      .el-date-picker,
      .el-input {
        width: 200px;
        input {
          cursor: pointer;
        }
      }
      .jeicon-user-cfg {
        font-size: 14px;
        line-height: 28px;
      }
      .spliter {
        font-size: 12px;
        color: #dcdfe6;
      }
    }
    .el-dropdown {
      color: #ffffff;
      background: #386bd0;
      border-radius: 15px;
      cursor: pointer;
      padding: 0 10px;
      line-height: 24px;
    }
  }
  .log-content {
    padding: 10px 20px 20px;
    height: 430px;
    overflow: auto;
    .label-top,
    .text-num {
      line-height: 24px;
      color: #999999;
    }
    .text-num {
      text-align: right;
    }
    .el-textarea {
      textarea {
        min-height: 90px !important;
      }
    }
  }
  .label-top {
    &.hasAnimation {
      background: #ffffff;
      &.active {
        -webkit-backface-visibility: hidden;
        -webkit-transform-style: preserve-3d;
        animation: BGHighlight 2s;
        animation-fill-mode:forwards;
      }
    }
    .uploadbtn {
      color: #396ad1;
      cursor: pointer;
    }
  }
  .buttonbar {
    text-align: right;
    padding: 10px 15px;
    &.home-log {
      background: #f5f7fe;
      padding: 11px 15px;
    }
    .class_wrp {
      cursor: pointer;
      float: left;
      line-height: 28px;
      > span {
        color: #386bd0;
        &:not(:first-child) {
          margin-left: 10px;
        }
      }
    }
    .button {
      width: 90px;
      line-height: 28px;
      text-align: center;
      background: #396ad1;
      color: #ffffff;
      display: inline-block;
      font-size: 14px;
      border-radius: 4px;
      cursor: pointer;
      margin: 0 5px;
      &.button-link {
        color: #396ad1;
        background: transparent;
      }
    }
  }
}

.el-date-table .available .haveLog:after {
  position: absolute;
  content: " ";
  padding: 2px;
  border-radius: 100%;
  bottom: -4px;
  left: 50%;
  margin-left: -2px;
  background: #2f6bcf;
}
.el-date-table .available .noLog:after {
  position: absolute;
  content: " ";
  padding: 0;
  border-radius: 100%;
  bottom: -4px;
  left: 50%;
  margin-left: -2px;
  background: #2f6bcf;
}
@keyframes BGHighlight {
  0% {
    background: #cae8fe;
  }
  50% {
    background: #ffffff;
  }
  100% {
    background: #ffffff;
  }
}
</style>
<template>
  <div
    v-loading="loading"
    class="pro-gzq-home-log"
  >
    <div
      v-show="!visible"
      @click="setVisible(true)"
      class="empty-box"
    >
      <i class="jeicon jeicon-signing" />
      {{ $t('_log.tijiaorizhi') }}
    </div>
    <div
      v-show="visible"
      class="content-box"
    >
      <div class="searchbar">
        <!-- 日志类型 -->
        <el-dropdown
          @command="changeType"
          placement="bottom"
        >
          <span class="el-dropdown-link">
            {{ getEn(activeType.text) }}<i class="el-icon-caret-bottom el-icon--right" />
          </span>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item
              v-for="(item) in types"
              :key="item"
              :command="item.code"
            >
              {{ getEn(item.text) }}
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
        <div class="inputbox">
          {{ $t('_log.date') }}:
          <el-date-picker
            ref="date"
            v-model="date"
            @focus="clickDate"
            :type="activeType.inputType"
            :format="activeType.format"
            :editable="false"
            :placeholder="$t('_log.xuanzeriqi')"
            size="mini"
          />
          {{ $t('_log.reuser') }}:
          <el-input
            ref="user"
            :placeholder="$t('_log.xuanzedianpingren')"
            @focus="selectUser"
            @clear="clearUser"
            v-model="data.REPORT_DPR_NAME"
            size="mini"
            clearable
          >
            <i
              slot="prefix"
              class="jeicon jeicon-user-cfg"
            />
          </el-input>
        </div>
      </div>
      <div
        v-loading="loading"
        class="log-content"
      >
        <div class="item">
          <div class="label-top hasAnimation">
            {{ getEn(activeType.workText) }}{{ $t('_log.gongzuozongjie') }}<span style="color: red;">*</span>：
          </div>
          <el-input
            ref="work"
            v-model="data.REPORT_GZZJ"
            @change="changeContent"
            type="textarea"
            resize="none"
            maxlength="1000"
            autosize
          />
          <div class="text-num">
            {{ (data.REPORT_GZZJ || '').length }}/1000
          </div>
        </div>
        <div class="item">
          <div class="label-top hasAnimation">
            {{ $t('_log.weiwancheng') }}：
          </div>
          <el-input
            ref="undone"
            v-model="data.REPORT_DWC"
            @change="changeContent"
            type="textarea"
            resize="none"
            maxlength="1000"
            autosize
          />
          <div class="text-num">
            {{ (data.REPORT_DWC || '').length }}/1000
          </div>
        </div>
        <div class="item">
          <div class="label-top hasAnimation">
            {{ getEn(activeType.planText) }}{{ $t('_log.gongzuojihua') }}：
          </div>
          <el-input
            ref="plan"
            v-model="data.REPORT_GZJH"
            @change="changeContent"
            type="textarea"
            resize="none"
            maxlength="1000"
            autosize
          />
          <div class="text-num">
            {{ (data.REPORT_GZJH || '').length }}/1000
          </div>
        </div>
        <div
          v-show="showsummary"
          class="item"
        >
          <div class="label-top hasAnimation">
            {{ $t('_log.gonzuoxinde') }}：
          </div>
          <el-input
            ref="summary"
            v-model="data.REPORT_GZXD"
            @change="changeContent"
            type="textarea"
            resize="none"
            maxlength="1000"
            autosize
          />
          <div class="text-num">
            {{ (data.REPORT_GZXD || '').length }}/1000
          </div>
        </div>
        <uploadbox
          ref="upload"
          v-show="showupload"
          :list="fileList"
          @upload="getList"
          :max="6"
        />
      </div>
      <div class="buttonbar home-log">
        <div class="class_wrp">
          <span
            v-for="(item, index) in logQuickList"
            :key="index"
            @click="handleQuickList(item, index)"
          >
            <span v-show="showAdd(item)">+</span>{{ getEn(getLabel(item)) }}
          </span>
        </div>
        <div
          @click="showList"
          class="button button-link"
        >
          {{ $t('_log.history') }}
        </div>
        <div
          @click="updateInfo"
          class="button"
        >
          {{ $t('_log.release') }}
        </div>
      </div>
    </div>
    <log-list ref="list" />
  </div>
</template>

<script>
import VueI18n from 'vue-i18n';
import LogList from './log_list.vue';
import uploadbox from '../../components/uploadbox';
import spe from '../../assets/lang/log/speNationalList';
import getLang from '../../assets/lang/mergeLang';

const i18n = new VueI18n({
  locale: JE.getCookies('je-local-lang') || 'zh_CN', // 语言标识
  messages: {
    zh_CN: getLang('zh', [{ name: '_log', data: require('./../../assets/lang/log/zh') }]), // 中文语言包
    en: getLang('en', [{ name: '_log', data: require('./../../assets/lang/log/en') }]), // 英文语言包
  },
});

export default {
  name: 'Log',
  components: { LogList, uploadbox },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
  },
  i18n,
  data() {
    return {
      visible: this.visible,
      loading: true,
      types: [
        {
          code: 'RZ', text: '日志', inputType: 'date', format: 'yyyy-MM-dd', workText: '今日', planText: '明日',
        },
        {
          code: 'ZB', text: '周报', inputType: 'week', format: 'yyyy 第 WW 周', workText: '本周', planText: '下周',
        },
        {
          code: 'YB', text: '月报', inputType: 'month', format: 'yyyy-MM', workText: '本月', planText: '下月',
        },
      ],
      activeType: {},
      date: new Date(),
      data: {},
      edited: false,
      logDates: [],
      dataBtnList: [],
      newActiveType: '',
      fileList: [],
      logQuickList: [],
      quickActive: {},
      showsummary: false,
      showupload: false,
    };
  },
  watch: {
    date(nv, ov) {
      if (JE.isEmpty(nv)) {
        this.date = new Date();
      }
      this.loadInfo();
    },
  },
  mounted() {
    const me = this;
    me.loadInfo(me.types[0]);
    this.newActiveType = this.types[0];
    this.logQuickList = [
      {
        label: '已完成工作',
        value: 'work',
      },
      {
        label: '未完成工作',
        value: 'undone',
      },
      {
        label: `${this.newActiveType.planText}计划`,
        value: 'plan',
      },
      {
        label: '工作心得',
        value: 'summary',
      },
      {
        label: '附件',
        value: 'upload',
      },
    ];
    this.quickActive = this.logQuickList[0];
  },
  methods: {
    handleQuickList(item, i) {
      if (item.value == 'summary' || item.value == 'upload') {
        this[`show${item.value}`] = true;
      }
      this.$nextTick(() => {
        this.quickActive = item;
        document.querySelector('.log-content').scrollTop = this.$refs[item.value].$el.offsetTop - 82;
        // debugger;
        // let timer = null;
        // let top = document.querySelector('.log-content').scrollTop;
        // const target = this.$refs[item.value].$el.offsetTop - 82;
        // clearInterval(timer);
        // if (top > target) {
        //   timer = setInterval(() => {
        //     if (top <= target) {
        //       clearInterval(timer);
        //     }
        //     top -= 10;
        //   }, 10);
        // } else {
        //   timer = setInterval(() => {
        //     if (top >= target) {
        //       clearInterval(timer);
        //     }
        //     top += 10;
        //   }, 10);
        // }
        const el = document.querySelectorAll('.label-top.hasAnimation')[i];
        const elClass = el.className;
        el.className = `${elClass} active`;
        setTimeout(() => {
          el.className = el.className.replace(/ active/g, '');
        }, 1000);
      });
    },
    getLabel(item) {
      if (item.value === 'plan') {
        return `${this.newActiveType.planText}计划`;
      }
      return item.label;
    },
    showAdd(item) {
      if (item.value == 'summary' || item.value == 'upload') {
        return !this[`show${item.value}`];
      }
      return false;
    },
    setVisible(visible) {
      this.$emit('setVisible', visible);
      this.$refs.list.setVisible(false);
    },
    showList(index, item) {
      // 此处需要处理页面数据重新加载
      const { list } = this.$refs;
      list.setVisible(true);
    },
    /**
     * 修改标记
     */
    changeContent(content) {
      const me = this;
      me.edited = true;
    },
    /**
     * 切换类型
     */
    changeType(code) {
      const me = this; let
        activeType;
      this.dataBtnList = [];
      Ext.each(this.types, (type) => {
        if (type.code == code) {
          activeType = type;
          me.$set(me, 'newActiveType', type);
          // me.newActiveType = type;
          return false;
        }
      });
      // 根据改动标记判断
      if (me.edited) {
        JE.confirm(`${me.$t('alert.needsaveit')}？`, (btn) => {
          if (btn == 'ok') {
            me.updateInfo(() => {
              me.loadInfo(activeType);
            });
          } else {
            me.loadInfo(activeType);
          }
        }, this.$t('remind'), this.$t('save'));
      } else {
        me.loadInfo(activeType);
      }
    },
    clearDate() {
      const me = this;
      me.date = new Date();
    },
    clearUser() {
      const me = this;
      me.data.REPORT_DPR_NAME = '',
      me.data.REPORT_DPR_ID = '';
      me.clearing = true;
      setTimeout(() => {
        me.$refs.user.blur();
        me.clearing = false;
      }, 100);
    },
    /**
     * 选择点评人
     */
    selectUser() {
      const me = this;
      if (me.clearing) { return; }
      me.$refs.user.blur();

      JE.vue.selectUser({
        title: me.$t('selectreviewers'),
        // width: 300,
        // height: 500,
        multiple: true,
        value: me.data.REPORT_DPR_ID,
        valueType: 'id',
        callback(datas) {
          const ids = []; const
            texts = [];
          // 点评人去除本人
          const newDatas = datas.filter(item => item.id !== JE.getCurrentUser().id);
          Ext.each(newDatas, (data) => {
            ids.push(data.id);
            texts.push(data.text);
          });

          if (ids.length > 0) {
            me.data.REPORT_DPR_ID = ids.join(',');// 点评人
            me.data.REPORT_DPR_NAME = texts.join(',');// 点评人姓名
          }
        },
      });
    },
    // 点击日期选择input框  有日志的日期添加下面的小圆点标记
    clickDate(d) {
      if (d instanceof Date) {
        this.loadInfo(this.newActiveType, d);
      } else {
        this.loadInfo(this.newActiveType);
      }
      setTimeout(() => {
        this.btnClick();
        const dateTags = document.getElementsByClassName('available');
        for (let i = 0; i < dateTags.length; i++) {
          var div = dateTags[i].children[0];
          if (div.localName === 'div') {
            div.className = 'noLog';
            if (this.logDates.length > 0) {
              this.logDates.forEach((item, index) => {
                const day = parseInt(item.substring(item.length - 2));
                if (day == div.innerText) {
                  div.className = 'haveLog';
                }
              });
            }
          }
        }
      }, 500);
    },
    btnClick() {
      const that = this;
      if (this.dataBtnList.length > 0) return;
      this.dataBtnList = document.querySelectorAll('.el-picker-panel__icon-btn');
      this.dataBtnList.forEach((item) => {
        item.addEventListener('click', (e) => {
          that.$nextTick(() => {
            const y = document.querySelectorAll('.el-date-picker__header-label')[0].innerText.split(' ')[0];
            const m = document.querySelectorAll('.el-date-picker__header-label')[1].innerText.split(' ')[0];
            const nd = `${y}/${m}/01`;
            that.clickDate(new Date(nd));
          });
        });
      });
    },
    /**
     * 加载数据
     */
    loadInfo(activeType, d) {
      const me = this; const
        date = d || me.date;
      me.edited = false;
      me.activeType = activeType || me.activeType;
      const type = me.activeType.code;
      const dateVal = Ext.Date.format(me.getTimes(date).start, type == 'YB' ? 'Y-m' : 'Y-m-d');
      me.loading = true;
      me.fileList = [];
      JE.ajax({
        url: '/je/portal/homePortal/loadWorkTask',
        params: {
          type,
          dateVal,
        },
        async: true,
        success(response) {
          const data = JE.getAjaxData(response);
          me.logDates = data.haveDates;

          if (data.success) {
            me.data = data.obj;
            if (data.obj.REPORT_FJ) {
              me.fileList = JSON.parse(data.obj.REPORT_FJ);
            } else {
              me.fileList = [];
            }
          } else {
            me.data = {
              REPORT_DPR_ID: JE.currentUser.zsldId, // 点评人
              REPORT_DPR_NAME: JE.currentUser.zsldName, // 点评人姓名
            };
          }
          me.showsummary = me.data.REPORT_GZXD;
          me.showupload = me.fileList.length > 0;
          me.$refs.work.focus();
          me.loading = false;
        },
      });
    },
    /**
     * 修改数据
     */
    updateInfo(callback) {
      const me = this;
      const content = (me.data.REPORT_GZZJ || '').trim();
      if (JE.isEmpty(me.date)) {
        JE.alert(`${this.$t('_log.selectdate')}!`);
        return;
      }
      if (JE.isEmpty(content)) {
        JE.alert(`${this.$t('_log.fillinworksummary')}!`);
        // me.$refs.summary.focus();
        return;
      }
      if (content.length > 1000) {
        return JE.msg('今日工作总结字数不能超过1000！');
      }
      if ((me.data.REPORT_DWC || '').trim().length > 1000) {
        return JE.msg('未完成工作内容字数不能超过1000！');
      }
      if ((me.data.REPORT_GZJH || '').trim().length > 1000) {
        return JE.msg('明日工作计划字数不能超过1000！');
      }
      if ((me.data.REPORT_GZXD || '').trim().length > 1000) {
        return JE.msg('工作心得总结字数不能超过1000！');
      }
      if (JE.isEmpty(me.data.REPORT_DPR_ID)) {
        return JE.alert(`${this.$t('_log.pleaseselectreviewers')}!`);
      }
      const times = me.getTimes();
      const data = {
        tableCode: 'JE_CIRCLE_REPORT',
        JE_CIRCLE_REPORT_ID: me.data.JE_CIRCLE_REPORT_ID || '',
        REPORT_BGLX_CODE: me.activeType.code, // 类型
        REPORT_GZZJ: me.data.REPORT_GZZJ, // 工作总结
        REPORT_DWC: me.data.REPORT_DWC, // 未完成工作内容
        REPORT_GZJH: me.data.REPORT_GZJH || '', // 工作计划
        REPORT_GZXD: me.data.REPORT_GZXD || '', //  心得总结
        REPORT_DPXX: me.data.REPORT_DPXX || '', // 点评内容
        REPORT_DPR_ID: me.data.REPORT_DPR_ID || '', // 点评人
        REPORT_DPR_NAME: me.data.REPORT_DPR_NAME || '', // 点评人姓名
        REPORT_KSSJ: times.startStr, // 开始时间
        REPORT_JSSJ: times.endStr, // 结束时间
        REPORT_YEAR: times.start.getFullYear(), // 年
        REPORT_MONTH: times.start.getMonth() + 1, // 月
        REPORT_WEEK: Ext.Date.getWeekOfYear(times.start), // 年第几周
        REPORT_DAY: times.start.getDate(), // 日
        REPORT_FJ: JSON.stringify(this.fileList), // 附件列表
      };
      me.loading = true;
      JE.ajax({
        url: '/je/workLog/saveTask',
        params: data,
        async: true,
        success(response) {
          const data = JE.getAjaxData(response);
          if (data.success) {
            me.data = data.obj;
            JE.msg(`${me.$t('alert.savesuccessfully')}!`);
            me.edited = false;
          } else {
            JE.alert(data.obj);
          }
          if (callback && typeof callback == 'function') {
            callback();
          } else {
            me.loading = false;
          }
        },
      });
    },
    /**
     * 时间
     */
    getTimes(d) {
      const me = this; const date = d || me.date; const
        type = me.activeType.code;
      let start = ''; let startStr = ''; let end = ''; let
        endStr = '';
      if (type == 'RZ') {
        start = end = date;
        startStr = endStr = Ext.Date.format(date, 'Y-m-d');
      } else if (type == 'ZB') {
        const week = date.getDay() || 7;
        start = new Date(date.getFullYear(), date.getMonth(), date.getDate() + (1 - week));
        end = new Date(date.getFullYear(), date.getMonth(), date.getDate() + (7 - week));
        startStr = Ext.Date.format(start, 'Y-m-d');
        endStr = Ext.Date.format(end, 'Y-m-d');
      } else if (type == 'YB') {
        start = Ext.Date.getFirstDateOfMonth(date);
        end = Ext.Date.getLastDateOfMonth(date);
        startStr = Ext.Date.format(start, 'Y-m-d');
        endStr = Ext.Date.format(end, 'Y-m-d');
      }
      return {
        start, end, startStr, endStr,
      };
    },
    getList(list) {
      this.fileList = list;
    },
    getEn(cn) {
      if (!cn) return;
      if (this.$i18n.locale == 'zh_CN') return cn;
      return spe[cn] || cn;
    },
  },
};
</script>
